#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>


#define TIMEOUT 5 /* select timeout in seconds */
#define BUF_LEN 1024 /* read buffer in bytes */


int main (void)
{
    struct timeval tv;
    // fd_set readfds;
    fd_set writefds;
    int ret;

    /* wait on stdin for input */
    FD_ZERO(&writefds);
    // FD_SET(STDIN_FILENO, &readfds);
    FD_SET(STDOUT_FILENO, &writefds);

    /* wait up to 5 seconds*/
    tv.tv_sec = TIMEOUT;
    tv.tv_usec = 0;

    /* all right, now block */
    ret = select (STDIN_FILENO + 1,
                &writefds,
                NULL,
                NULL,
                &tv);
    if (ret == -1) {
        perror("select");
        return 1;
    } else if (!ret) {
        printf("%d seconds elapsed.", TIMEOUT);
        return 0;
    }

    /* our file descriptor ready to read? */
    if (FD_ISSET(STDOUT_FILENO, &writefds)) {
        char buf[BUF_LEN+1];
        int len;

        len = read(STDOUT_FILENO, buf, BUF_LEN);
        if (len == -1) {
            perror("read");
            return 1;
        }

        if (len) {
            buf[len] = '\0';
            printf("read: %s\n", buf);
        }

        return 0;
    }

    fprintf(stderr, "this should not happen!\n");

    return 1;
}
